// PTZ API 工具类 - 适配 wvp-GB28181-pro 的接口

class PtzApi {
  constructor(baseUrl = '', token = '', useProxy = true) {
    this.baseUrl = baseUrl.replace(/\/$/, ''); // 移除末尾斜杠
    this.token = token;
    this.useProxy = useProxy; // 是否使用Next.js代理
  }

  // 设置基础URL和认证token
  setConfig(baseUrl, token, useProxy = true) {
    this.baseUrl = baseUrl.replace(/\/$/, '');
    this.token = token;
    this.useProxy = useProxy;
  }

  // 通用请求方法
  async request(url, options = {}) {
    let fullUrl;
    
    if (this.useProxy) {
      // 使用Next.js代理路由
      fullUrl = `/api/ptz${url}`;
    } else {
      // 直接访问wvp服务（可能遇到CORS问题）
      fullUrl = `${this.baseUrl}${url}`;
    }

    const headers = {
      'Content-Type': 'application/json',
      ...options.headers
    };

    if (this.token) {
      // WVP API Key认证方式
      headers['X-API-Key'] = this.token;
      headers['Authorization'] = `ApiKey ${this.token}`;
    }

    const config = {
      ...options,
      headers
    };

    try {
      const response = await fetch(fullUrl, config);
      
      if (!response.ok) {
        throw new Error(`HTTP ${response.status}: ${response.statusText}`);
      }

      const data = await response.json();
      
      // 假设API返回格式为 { code: 0, data: {...}, msg: "success" }
      if (data.code !== undefined && data.code !== 0) {
        throw new Error(data.msg || '请求失败');
      }

      return data.data || data;
    } catch (error) {
      console.error('API请求失败:', error);
      throw error;
    }
  }

  // PTZ控制 - 方向和缩放
  async ptz(deviceId, channelId, command, horizonSpeed, verticalSpeed, zoomSpeed) {
    const url = `/api/front-end/ptz/${deviceId}/${channelId}`;
    const params = new URLSearchParams({
      command,
      horizonSpeed: horizonSpeed.toString(),
      verticalSpeed: verticalSpeed.toString(),
      zoomSpeed: zoomSpeed.toString()
    });

    return this.request(`${url}?${params}`, { method: 'GET' });
  }

  // 聚焦控制
  async focus(deviceId, channelId, command, speed) {
    const url = `/api/front-end/fi/focus/${deviceId}/${channelId}`;
    const params = new URLSearchParams({
      command,
      speed: speed.toString()
    });

    return this.request(`${url}?${params}`, { method: 'GET' });
  }

  // 光圈控制
  async iris(deviceId, channelId, command, speed) {
    const url = `/api/front-end/fi/iris/${deviceId}/${channelId}`;
    const params = new URLSearchParams({
      command,
      speed: speed.toString()
    });

    return this.request(`${url}?${params}`, { method: 'GET' });
  }

  // 查询预置点
  async queryPreset(deviceId, channelId) {
    const url = `/api/front-end/preset/query/${deviceId}/${channelId}`;
    return this.request(url, { method: 'GET' });
  }

  // 添加预置点
  async addPreset(deviceId, channelId, presetId) {
    const url = `/api/front-end/preset/add/${deviceId}/${channelId}`;
    const params = new URLSearchParams({
      presetId: presetId.toString()
    });

    return this.request(`${url}?${params}`, { method: 'GET' });
  }

  // 调用预置点
  async callPreset(deviceId, channelId, presetId) {
    const url = `/api/front-end/preset/call/${deviceId}/${channelId}`;
    const params = new URLSearchParams({
      presetId: presetId.toString()
    });

    return this.request(`${url}?${params}`, { method: 'GET' });
  }

  // 删除预置点
  async deletePreset(deviceId, channelId, presetId) {
    const url = `/api/front-end/preset/delete/${deviceId}/${channelId}`;
    const params = new URLSearchParams({
      presetId: presetId.toString()
    });

    return this.request(`${url}?${params}`, { method: 'GET' });
  }

  // 巡航相关接口
  async addPointForCruise(deviceId, channelId, cruiseId, presetId) {
    const url = `/api/front-end/cruise/point/add/${deviceId}/${channelId}`;
    const params = new URLSearchParams({
      cruiseId: cruiseId.toString(),
      presetId: presetId.toString()
    });

    return this.request(`${url}?${params}`, { method: 'GET' });
  }

  async deletePointForCruise(deviceId, channelId, cruiseId, presetId) {
    const url = `/api/front-end/cruise/point/delete/${deviceId}/${channelId}`;
    const params = new URLSearchParams({
      cruiseId: cruiseId.toString(),
      presetId: presetId.toString()
    });

    return this.request(`${url}?${params}`, { method: 'GET' });
  }

  async setCruiseSpeed(deviceId, channelId, cruiseId, speed) {
    const url = `/api/front-end/cruise/speed/${deviceId}/${channelId}`;
    const params = new URLSearchParams({
      cruiseId: cruiseId.toString(),
      speed: speed.toString()
    });

    return this.request(`${url}?${params}`, { method: 'GET' });
  }

  async setCruiseTime(deviceId, channelId, cruiseId, time) {
    const url = `/api/front-end/cruise/time/${deviceId}/${channelId}`;
    const params = new URLSearchParams({
      cruiseId: cruiseId.toString(),
      time: time.toString()
    });

    return this.request(`${url}?${params}`, { method: 'GET' });
  }

  async startCruise(deviceId, channelId, cruiseId) {
    const url = `/api/front-end/cruise/start/${deviceId}/${channelId}`;
    const params = new URLSearchParams({
      cruiseId: cruiseId.toString()
    });

    return this.request(`${url}?${params}`, { method: 'GET' });
  }

  async stopCruise(deviceId, channelId, cruiseId) {
    const url = `/api/front-end/cruise/stop/${deviceId}/${channelId}`;
    const params = new URLSearchParams({
      cruiseId: cruiseId.toString()
    });

    return this.request(`${url}?${params}`, { method: 'GET' });
  }

  // 扫描相关接口
  async setSpeedForScan(deviceId, channelId, scanId, speed) {
    const url = `/api/front-end/scan/set/speed/${deviceId}/${channelId}`;
    const params = new URLSearchParams({
      scanId: scanId.toString(),
      speed: speed.toString()
    });

    return this.request(`${url}?${params}`, { method: 'GET' });
  }

  async setLeftForScan(deviceId, channelId, scanId) {
    const url = `/api/front-end/scan/set/left/${deviceId}/${channelId}`;
    const params = new URLSearchParams({
      scanId: scanId.toString()
    });

    return this.request(`${url}?${params}`, { method: 'GET' });
  }

  async setRightForScan(deviceId, channelId, scanId) {
    const url = `/api/front-end/scan/set/right/${deviceId}/${channelId}`;
    const params = new URLSearchParams({
      scanId: scanId.toString()
    });

    return this.request(`${url}?${params}`, { method: 'GET' });
  }

  async startScan(deviceId, channelId, scanId) {
    const url = `/api/front-end/scan/start/${deviceId}/${channelId}`;
    const params = new URLSearchParams({
      scanId: scanId.toString()
    });

    return this.request(`${url}?${params}`, { method: 'GET' });
  }

  async stopScan(deviceId, channelId, scanId) {
    const url = `/api/front-end/scan/stop/${deviceId}/${channelId}`;
    const params = new URLSearchParams({
      scanId: scanId.toString()
    });

    return this.request(`${url}?${params}`, { method: 'GET' });
  }

  // 辅助控制
  async auxiliary(deviceId, channelId, command, switchId) {
    const url = `/api/front-end/auxiliary/${deviceId}/${channelId}`;
    const params = new URLSearchParams({
      command,
      switchId: switchId.toString()
    });

    return this.request(`${url}?${params}`, { method: 'GET' });
  }

  // 雨刷控制
  async wiper(deviceId, channelId, command) {
    const url = `/api/front-end/wiper/${deviceId}/${channelId}`;
    const params = new URLSearchParams({
      command
    });

    return this.request(`${url}?${params}`, { method: 'GET' });
  }
}

// 创建默认实例
const ptzApi = new PtzApi();

export default ptzApi;
export { PtzApi };